import { From, Public } from ".."
import type { TabsProps } from 'antd';
import { CalendarOutlined } from '@ant-design/icons';
import { Outlet } from '@/.umi/exports';
import locale from 'antd/es/date-picker/locale/en_US';
import type { FormInstance } from 'antd/es/form';
import dayjs from 'dayjs';
import { Button, DatePicker, Form, Input, Popconfirm, Table, Select, Typography, Modal, Tabs } from 'antd';
import type { InputRef, DatePickerProps } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';
const { Text } = Typography;
const EditableContext = React.createContext<FormInstance<any> | null>(null);
const time2string = (time: any) => {
    let time1 = time.split(' ')
    let yun = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    let montn
    yun.forEach((v, i) => {
        if (time1[1] == v) {
            montn = i + 1
        }
    })
    return time1[3] + '-' + montn + '-' + time1[2];
}
interface Item {
    key: string;
    name: string;
    age: string;
    address: string;
    alert: string
}
interface EditableRowProps {
    index: number;
}
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}
type EditableTableProps = Parameters<typeof Table>[0];
interface DataType {
    key: React.Key;
    name: string;
    alert: string
    age: any;
    address: string;
}
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
const Bank = () => {
        // 弹框
        const [isModalOpen, setIsModalOpen] = useState(false);
        const showModal = () => {
            setIsModalOpen(true);
        };
        const handleOk = () => {
            setIsModalOpen(false);
        };
        const handleCancel = () => {
            setIsModalOpen(false);
        };
        // 弹框表格数据
        const columns1 = [
            {
                title: '编号',
                dataIndex: 'name',
            },
            {
                title: '名称',
                dataIndex: 'age',
            },
        ];
        const data = [
            {
                key: '1',
                name: 'John Brown',
                age: 32,
                address: 'New York No. 1 Lake Park',
            },
            {
                key: '2',
                name: 'Jim Green',
                age: 42,
                address: 'London No. 1 Lake Park',
            },
            {
                key: '3',
                name: 'Joe Black',
                age: 32,
                address: 'Sydney No. 1 Lake Park',
            },
        ];
      // 选项卡
      const items: TabsProps['items'] = [
        {
            key: '1',
            label: '客户',
            children: <Table columns={columns1} dataSource={data} size="middle" />,
        },
        {
            key: '2',
            label: '供应商',
            children: 'Content of Tab Pane 2',
        },
    ];
    const onChange = (key: string) => {
        console.log(key);
    };
    // 可编辑单元格操作
    const EditableCell: React.FC<EditableCellProps> = ({
        title,
        editable,
        children,
        dataIndex,
        record,
        handleSave,
        ...restProps
    }) => {
        const [editing, setEditing] = useState(false);
        const [editing2, setEditing2] = useState(false);
        const [editing3, setEditing3] = useState(false);
        const [editing4, setEditing4] = useState(false);
        const inputRef = useRef<InputRef>(null);
        const selRef = useRef<InputRef>(null);
        const pickRef = useRef<InputRef>(null);
        const form = useContext(EditableContext)!;
        const [hhh, sethhh] = useState('')
        type PickerType = 'time' | 'date';
        const [type, setType] = useState<PickerType>('time');
        useEffect(() => {
            if (editing) {
                inputRef.current!.focus();
            }
        }, [editing]);

        const toggleEdit = () => {
            if (dataIndex == 'name') {
                setEditing(!editing);
            } else if (dataIndex == 'age') {
                setEditing2(!editing2);
            } else if (dataIndex == 'address') {
                setEditing3(!editing3);
            } else if (dataIndex == 'alert') {
                setEditing4(!editing4);
            }

            if (dataIndex == 'age') {
                form.setFieldsValue({ ...record, [dataIndex]: dayjs(record[dataIndex], 'YYYY-MM-DD') });
            } else {
                form.setFieldsValue({ ...record, [dataIndex]: record[dataIndex] });
            }


        };

        const save = async () => {
            try {
                const values = await form.validateFields();
                if (values.age) {
                    values.age = time2string(String(values.age.$d))
                }
                toggleEdit();
                handleSave({ ...record, ...values });
            } catch (errInfo) {
                console.log('Save failed:', errInfo);
            }
        };
        let childNode = children;

        if (editable) {
            if (editing) {
                childNode = <Form.Item
                    style={{ margin: 0 }}
                    name={dataIndex}
                >
                    <Input ref={inputRef} onPressEnter={save} onBlur={save} />
                </Form.Item>

            } else if (editing2) {
                childNode = <Form.Item

                    style={{ margin: 0 }}
                    name={dataIndex}
                >
                    <DatePicker onBlur={save} locale={locale} style={{ width: 200 }} />
                </Form.Item>
            } else if (editing3) {
                childNode = <Form.Item
                    style={{ margin: 0 }}
                    name={dataIndex}
                ><Select onBlur={save}
                    style={{ width: 120 }}
                    options={[
                        { value: 'aaa', label: 'aaa' },
                        { value: 'bbb', label: 'bbb' },
                        { value: 'ccc', label: 'ccc' },
                        { value: 'ddd', label: 'ddd' },
                    ]}
                    />
                </Form.Item>
            } else if (editing4) {
                childNode = <Form.Item
                    style={{ margin: 0 }}
                    name={dataIndex}>
                    <Button onClick={showModal}>
                        <CalendarOutlined />
                    </Button>
                    <Modal title="选择往来单位" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                        <Tabs defaultActiveKey="1" items={items} onChange={onChange} />;
                    </Modal>
                </Form.Item>
            }
            else {
                childNode = <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
                    {children}
                </div>
            }
        }

        return <td {...restProps}>{childNode}</td>;
    };
    // 表格数据
    const [dataSource, setDataSource] = useState<DataType[]>([
        {
            key: '0',
            name: 'Edward King 0',
            age: '2022-10-12',
            alert: 'bbb',
            address: 'aaa',
        },
        {
            key: '1',
            name: 'Edward King 1',
            alert: 'aaa',
            age: '2022-10-12',
            address: 'bbb',
        },
    ]);
    const [count, setCount] = useState(2);
    const handleDelete = (key: React.Key) => {
        const newData = dataSource.filter((item) => item.key !== key);
        setDataSource(newData);
    };
    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: '单据编号',
            dataIndex: 'name',
            width: '30%',
            // editable: true,
        },
        {
            title: '日期',
            dataIndex: 'age',
            editable: true,
        },
        {
            title: '摘要',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: '收支类别',
            dataIndex: 'address',
            editable: true,
        },
        {
            title: '收入(借方)',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: '支出(贷方)',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: '余额',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: '关联凭证',
            dataIndex: 'name',
            width: '30%',
            render: (text) => <a>{text}</a>
        },
        {
            title: '来往单位',
            dataIndex: 'alert',
            width: '30%',
            editable: true,
        },
        {
            title: '结算方式',
            dataIndex: 'address',
            editable: true,
        },
        {
            title: '票据号',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: '备注',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: 'operation',
            dataIndex: 'operation',
            render: (_, record: any) => (<>
                <a onClick={handleAdd}>下方添加</a>
                <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.key)}>
                    <a>删除</a>
                </Popconfirm>
                <a>打印</a>
            </>

            )
        },
    ];
    // 新增单元格
    const handleAdd = () => {
        const newData: DataType = {
            key: count,
            name: `Edward King ${count}`,
            age: <DatePicker locale={locale} style={{ width: 200 }} />,
            address: `London, Park Lane no. ${count}`,
            alert: ''
        };
        setDataSource([...dataSource, newData]);
        setCount(count + 1);
    };
    const handleSave = (row: DataType) => {
        const newData = [...dataSource];
        const index = newData.findIndex((item) => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        console.log(newData);

        setDataSource(newData);
    };
    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };
    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });
    return (
        <div>
            <Public header='银行日记账'></Public>
            {/* 操作和搜索框 */}
            <From type='记账银行'></From>
            <Table style={{ width: '98%', margin: 'auto', marginTop: 20 }}
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                columns={columns as ColumnTypes}
                summary={(data) => {
                    let ages = 0;
                    let repayments = 0;
                    data.forEach(({ age, repayment }) => {
                        if (age != null && repayment != null) {
                            ages += age
                            repayments += repayment
                        }

                    })
                    return (<>
                        <Table.Summary.Row>
                            <Table.Summary.Cell colSpan={4} index={0} className="total-cell">总计:</Table.Summary.Cell>
                            <Table.Summary.Cell colSpan={1} index={1}>
                                <Text>{ages}</Text>
                            </Table.Summary.Cell>
                            <Table.Summary.Cell colSpan={1} index={1}>
                                <Text>{repayments}</Text>
                            </Table.Summary.Cell>
                            <Table.Summary.Cell colSpan={1} index={1}>
                                <Text>{repayments}</Text>
                            </Table.Summary.Cell>
                            <Table.Summary.Cell index={1} colSpan={6} />
                        </Table.Summary.Row>
                    </>

                    )
                }}
            />
        </div>
    )
}
export default Bank